package controller.algo;

import java.util.ArrayList;
import java.util.NoSuchElementException;

import model.Edge;
import model.container.edges.*;
import model.container.vertices.*;

public class Kruskal extends Algo {
	private AdjacencyList vertices;
	private AdjacencyList verticesT;
	private Edges edges;
	private ArrayList<Edge> edgesN;
	
	private int cost = 0;

	public Kruskal() {
	}
	
	@Override
	public void loadEdges(Edges t) {
		edges = t;
	}

	@Override
	public void loadVertices(AdjacencyList v) {
		vertices = v;
	}

	@Override
	public ArrayList<Edge> getNewEdges() {
		return edgesN;
	}

	@Override
	public boolean process() {
		verticesT = new AdjacencyList();
		edgesN = new ArrayList<Edge>();

		Edge e = edges.getMinimal();
		//System.out.println(getClass()+" [+] Adding verified item "+e);
		verticesT.addItem(e);
		verticesT.addItem(e.revert());
		edgesN.add(e);

		cost = e.getCost();
		while(edgesN.size() < vertices.getSize()-1) {
			try {
				e = edges.getMinimal();
			} catch (NoSuchElementException f) {
				//System.out.println("edgesN.size() : "+edgesN.size()+" / vertices.getSize() : "+vertices.getSize());
				return false;
			}
			if(isVerified(e)) {
				//System.out.println(getClass()+" [+] Adding verified item "+e);
				verticesT.addItem(e);
				verticesT.addItem(e.revert());
				edgesN.add(e);
				cost = cost + e.getCost();
			}
		}

		return true;
	}

	private boolean isVerified(Edge e) {
		if(verticesT.getItemList(e.getFrom()) == null
				|| verticesT.getItemList(e.getTo()) == null
				|| verticesT.getDistance(e) == -1
				|| verticesT.getDistance(e.revert()) == -1)
			return true;
		return false;
	}
	
	public int getCost() {
		return cost;
	}
}

